<template>
  <el-container style="padding: 20px">
    <el-main>
      <template v-if="activeTab === 'receive'">
        <el-card>
          <el-form :inline="true">
            <el-form-item label="疫苗名称">
              <el-input
                v-model="searchName"
                placeholder="请输入疫苗名称"
                clearable
              />
            </el-form-item>
            <el-form-item label="疫苗编号">
              <el-input
                v-model="searchNumbering"
                placeholder="请输入疫苗编号"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </template>

      <el-card style="margin-top: 20px">
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <span style="font-weight: bold">
            {{ activeTab === 'receive' ? '疫苗列表' : '已领取记录' }}
          </span>
          <el-button
            v-if="activeTab === 'receive'"
            type="primary"
            :disabled="selectedVaccines.length !== 1"
            @click="openUsageDialog"
          >
            领取疫苗
          </el-button>
        </div>

        <!-- 疫苗表格 -->
        <el-table
          v-if="activeTab === 'receive'"
          :data="vaccines"
          @selection-change="handleVaccineSelect"
          style="margin-top: 10px"
          border
          height="320"
          v-loading="loadingVaccines"
          element-loading-text="加载中..."
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="numbering" label="疫苗编号" width="150" />
          <el-table-column prop="name" label="疫苗名称" width="150" />
          <el-table-column prop="amount" label="库存数量" width="100" />
          <el-table-column
            prop="productionDate"
            label="生产日期"
            width="130"
            :formatter="formatDate"
          />
          <el-table-column
            prop="inactivationDate"
            label="失效日期"
            width="130"
            :formatter="formatDate"
          />
          <el-table-column
            prop="nextCheckDate"
            label="下次核查日期"
            width="130"
            :formatter="formatDate"
          />
        </el-table>

        <el-pagination
          style="margin-top: 15px; text-align: right"
          background
          layout="prev, pager, next, jumper, ->, total"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          @current-change="handlePageChange"
        />
      </el-card>

      <!-- 领取弹窗 -->
      <el-dialog
        v-model="usageDialogVisible"
        title="领取疫苗"
        width="400px"
        destroy-on-close
        @close="resetUsageDialog"
      >
        <el-form :model="usageForm" ref="usageFormRef" label-width="100px">
          <el-form-item label="疫苗编号">
            <el-input v-model="usageForm.numbering" disabled />
          </el-form-item>
          <el-form-item label="疫苗名称">
            <el-input v-model="usageForm.name" disabled />
          </el-form-item>
          <el-form-item label="库存">
            <el-input-number v-model="usageForm.amount" disabled />
          </el-form-item>
          <el-form-item label="领取数量">
            <el-input-number
              v-model="usageForm.quantity"
              :min="1"
              :max="usageForm.amount"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="usageDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitUsage">确认领取</el-button>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const activeTab = ref('receive')
const searchName = ref('')
const searchNumbering = ref('')
const vaccines = ref([])
const usageRecords = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const loadingVaccines = ref(false)
const loadingUsage = ref(false)
const selectedVaccines = ref([])

const usageDialogVisible = ref(false)
const usageForm = reactive({
  numbering: '',
  name: '',
  amount: 0,
  quantity: 1,
})
const usageFormRef = ref(null)

function getDoctorId() {
  const user = JSON.parse(localStorage.getItem('user'))
  return user ? user.id : null
}

function formatDate(row, column, cellValue) {
  if (!cellValue) return ''
  const date = new Date(cellValue)
  const yyyy = date.getFullYear()
  const mm = String(date.getMonth() + 1).padStart(2, '0')
  const dd = String(date.getDate()).padStart(2, '0')
  return `${yyyy}--${mm}--${dd}`
}

async function loadVaccines() {
  loadingVaccines.value = true
  try {
    const res = await axios.get(
      `http://127.0.0.1:8181/vaccines/vaccineList/${currentPage.value}/${pageSize.value}`
    )
    if (res.data.code === 0) {
      let list = res.data.data.data || []
      if (searchName.value)
        list = list.filter((v) => v.name.includes(searchName.value))
      if (searchNumbering.value)
        list = list.filter((v) => v.numbering.includes(searchNumbering.value))
      vaccines.value = list
      total.value = res.data.data.total || list.length
    } else {
      ElMessage.error('获取疫苗列表失败')
    }
  } catch (e) {
    ElMessage.error('请求疫苗列表出错')
  } finally {
    loadingVaccines.value = false
  }
}

function handleSearch() {
  currentPage.value = 1
  loadVaccines()
}

function handlePageChange(page) {
  currentPage.value = page
  loadVaccines()
}

function handleVaccineSelect(selection) {
  selectedVaccines.value = selection
}

function openUsageDialog() {
  if (selectedVaccines.value.length !== 1) {
    ElMessage.warning('请选择一条疫苗进行领取')
    return
  }
  const v = selectedVaccines.value[0]
  usageForm.numbering = v.numbering
  usageForm.name = v.name
  usageForm.amount = v.amount
  usageForm.quantity = 1
  usageDialogVisible.value = true
}

function resetUsageDialog() {
  usageForm.numbering = ''
  usageForm.name = ''
  usageForm.amount = 0
  usageForm.quantity = 1
  if (usageFormRef.value) usageFormRef.value.clearValidate()
}

async function submitUsage() {
  if (usageForm.quantity < 1 || usageForm.quantity > usageForm.amount) {
    ElMessage.error('领取数量不合法')
    return
  }
  try {
    const doctorId = getDoctorId()
    const res = await axios.post(
      'http://127.0.0.1:8181/doctor/usage',
      {
        vaccineNumbering: usageForm.numbering,
        quantityUsed: usageForm.quantity,
      },
      {
        headers: {
          doctorId,
        },
      }
    )
    if (res.data.code === 0) {
      ElMessage.success('领取成功')
      usageDialogVisible.value = false
      loadVaccines()
    } else {
      ElMessage.error('领取失败')
    }
  } catch (e) {
    ElMessage.error('请求失败')
  }
}

// 页面卸载时强制关闭弹窗，避免切换菜单残留
onUnmounted(() => {
  usageDialogVisible.value = false
  resetUsageDialog()
})

onMounted(() => {
  loadVaccines()
})
</script>
